package me.zhengjie.modules.website.service.impl;

import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.website.domain.ColumnTable;
import me.zhengjie.modules.website.domain.ContentTable;
import me.zhengjie.modules.website.domain.UserColumn;
import me.zhengjie.modules.website.repository.ColumnTableRepository;
import me.zhengjie.modules.website.repository.ContentTableRepository;
import me.zhengjie.modules.website.repository.ContentTableSpecifications;
import me.zhengjie.modules.website.service.ColumnTableService;
import me.zhengjie.modules.website.service.ContentTableService;
import me.zhengjie.modules.website.service.UserColumnService;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import me.zhengjie.modules.website.domain.PageResult;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
 * @author system
 * @since 2024-09-26 16:41:54
 */
@Service
public class ContentTableServiceImpl implements ContentTableService {

    @Autowired
    private ContentTableRepository contentTableRepository;

    @Autowired
    private ColumnTableRepository columnTableRepository;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserColumnService userColumnService;

    @Autowired
    private ColumnTableService columnTableService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //    @Override
//    public PageResult<ContentTable> findPage(ContentTable contentTable, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) {
//        Page<ContentTable> page = contentTableRepository.findAll((root, query, criteriaBuilder) -> {
//            List<Predicate> predicates = new ArrayList<>();
//
//            // 通过反射遍历 ContentTable 的所有字段，过滤静态字段
//            for (Field field : ContentTable.class.getDeclaredFields()) {
//                field.setAccessible(true); // 允许访问私有字段
//
//                // 跳过静态字段
//                if (Modifier.isStatic(field.getModifiers())) {
//                    continue;
//                }
//
//                try {
//                    Object value = field.get(contentTable); // 获取字段值
//                    if (value != null) {
//                        // 对 title 字段使用模糊匹配
//                        if ("title".equals(field.getName())) {
//                            predicates.add(criteriaBuilder.like(root.get(field.getName()), "%" + value + "%"));
//                        } else {
//                            predicates.add(criteriaBuilder.equal(root.get(field.getName()), value));
//                        }
//                    }
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            // 时间范围条件
//            if (startDate != null) {
//                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(startDate)));
//            }
//            if (endDate != null) {
//                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(endDate)));
//            }
//
//            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
//        }, pageable);
//
//        PageResult<ContentTable> result = new PageResult<>();
//        result.setContent(page.getContent());
//        result.setTotalElements(page.getTotalElements());
//        return result;
//    }
    @Override
    public PageResult<ContentTable> findPage(ContentTable contentTable, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) {
        // 获取用户的角色id
        List<RoleSmallDto> byUsersId = roleService.findByUsersId(SecurityUtils.getCurrentUserId());

        // 获取用户角色对应的栏目对象
        List<UserColumn> userColumns = new ArrayList<>();
        for (RoleSmallDto roleSmallDto : byUsersId) {
            UserColumn userColumn = new UserColumn();
            userColumn.setRoleId(roleSmallDto.getId());
            userColumns.addAll(userColumnService.findList(userColumn));
        }

        // 获取所有的 columnId
        List<String> userColumnIds = userColumns.stream()
                .map(userColumn -> String.valueOf(userColumn.getColumnId()))
                .collect(Collectors.toList());

        Page<ContentTable> page = contentTableRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 通过反射遍历 ContentTable 的所有字段，过滤静态字段
            for (Field field : ContentTable.class.getDeclaredFields()) {
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                field.setAccessible(true); // 允许访问私有字段
                try {
                    Object value = field.get(contentTable);
                    if (value != null) {
                        if ("title".equals(field.getName())) {
                            predicates.add(criteriaBuilder.like(root.get("title"), "%" + value + "%"));
                        } else {
                            predicates.add(criteriaBuilder.equal(root.get(field.getName()), value));
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 时间范围条件
            if (startDate != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(startDate)));
            }
            if (endDate != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(endDate)));
            }

            // 根据 columnIds 过滤
            if (contentTable.getColumnIds() == null && !userColumnIds.isEmpty()) {
                Predicate columnIdPredicate = criteriaBuilder.or(userColumnIds.stream()
                        .map(columnId -> criteriaBuilder.like(root.get("columnIds"), "%" + columnId + "%"))
                        .toArray(Predicate[]::new));
                predicates.add(columnIdPredicate);
            }

            // **过滤掉超出范围的 releaseTime**
            Predicate validReleaseTime = criteriaBuilder.between(
                    root.get("releaseTime"),
                    Timestamp.valueOf("1000-01-01 00:00:00"),
                    Timestamp.valueOf("9999-12-31 23:59:59")
            );
            predicates.add(validReleaseTime);

            // 设置排序规则
            if (pageable.getSort() == null || pageable.getSort().isEmpty()) {
                // 先按照 sort_order 降序排列，sort_order 越大越靠前
                Expression<Integer> sortOrderExpression = root.get("sortOrder");
                Expression<Date> releaseTimeExpression = root.get("releaseTime");

                // 处理sortOrder为null的情况
                Order sortOrderSort = criteriaBuilder.desc(criteriaBuilder.coalesce(sortOrderExpression, Integer.MIN_VALUE));

                // 处理releaseTime为null的情况，避免 LocalDateTime.MAX 溢出
                Expression<Object> safeReleaseTime = criteriaBuilder.selectCase()
                        .when(criteriaBuilder.isNull(releaseTimeExpression), Timestamp.valueOf("1000-12-31 23:59:59"))
                        .otherwise(releaseTimeExpression);

                // 按 release_time 降序排列，release_time 为 null 的排到最后
                Order releaseTimeSort = criteriaBuilder.desc(safeReleaseTime);

                query.orderBy(sortOrderSort, releaseTimeSort);
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        }, pageable);

        PageResult<ContentTable> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }


   /* @Override
    public PageResult<ContentTable> findPageToManage(ContentTable contentTable, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) {
        // 获取当前用户的角色id
        List<RoleSmallDto> byUsersId = roleService.findByUsersId(SecurityUtils.getCurrentUserId());
        // 获取用户角色对应的栏目对象
        List<UserColumn> userColumns = new ArrayList<>();

        for (RoleSmallDto roleSmallDto : byUsersId) {
            UserColumn userColumn = new UserColumn();
            userColumn.setRoleId(roleSmallDto.getId());
            userColumns.addAll(userColumnService.findList(userColumn));
        }

        // 获取所有的 columnId
        List<String> userColumnIds = userColumns.stream()
                .map(userColumn -> String.valueOf(userColumn.getColumnId()))
                .collect(Collectors.toList());

        Page<ContentTable> page = contentTableRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 通过反射遍历 ContentTable 的所有字段，过滤静态字段
            for (Field field : ContentTable.class.getDeclaredFields()) {
                field.setAccessible(true); // 允许访问私有字段

                // 跳过静态字段
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                try {
                    Object value = field.get(contentTable); // 获取字段值
                    if (value != null) {
                        // 对 title 字段使用模糊匹配
                        if ("title".equals(field.getName())) {
                            predicates.add(criteriaBuilder.like(root.get(field.getName()), "%" + value + "%"));
                        } else if ("columnIds".equals(field.getName())) {
                            // 对 columnIds 使用模糊匹配
                            predicates.add(criteriaBuilder.like(root.get(field.getName()), "%" + value + "%"));
                        } else {
                            predicates.add(criteriaBuilder.equal(root.get(field.getName()), value));
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 时间范围条件
            if (startDate != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(startDate)));
            }
            if (endDate != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(endDate)));
            }

            // 根据 columnIds 过滤，确保用户拥有相关栏目权限
            if (contentTable.getColumnIds() == null && !userColumnIds.isEmpty()) {
                Predicate columnIdPredicate = criteriaBuilder.or(userColumnIds.stream()
                        .map(columnId -> criteriaBuilder.like(root.get("columnIds"), "%" + columnId + "%"))
                        .toArray(Predicate[]::new));
                predicates.add(columnIdPredicate);
            }

            // 设置排序规则
            if (pageable.getSort() == null || pageable.getSort().isEmpty()) {
                // 默认排序，先按照 sortOrder 排序，值越小越前，若为null则按 releaseTime 排序，时间越久越靠后
                Expression<Integer> sortOrderExpression = root.get("sortOrder");
                Expression<Date> releaseTimeExpression = root.get("releaseTime");

                // 处理sortOrder为null的情况
                Order sortOrderSort = criteriaBuilder.asc(criteriaBuilder.coalesce(sortOrderExpression, Integer.MAX_VALUE));

                // 处理releaseTime为null的情况
                Order releaseTimeSort = criteriaBuilder.asc(criteriaBuilder.coalesce(releaseTimeExpression, Timestamp.valueOf(LocalDateTime.MAX)));

                // 将排序规则添加到查询中
                query.orderBy(sortOrderSort, releaseTimeSort);
            } else {
                // 如果 pageable 有排序条件，则使用 pageable 中的排序
                List<Order> orders = new ArrayList<>();
                pageable.getSort().forEach(order -> {
                    if (order.isAscending()) {
                        orders.add(criteriaBuilder.asc(root.get(order.getProperty())));
                    } else {
                        orders.add(criteriaBuilder.desc(root.get(order.getProperty())));
                    }
                });
                query.orderBy(orders);
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        }, pageable);

        // 构建并返回结果
        PageResult<ContentTable> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }*/


    @Override
    public PageResult<ContentTable> findLikeColumnId(ContentTable contentTable, LocalDateTime startDate, LocalDateTime endDate, Pageable pageable) {
        // 执行分页查询
        Page<ContentTable> page = contentTableRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 通过反射遍历 ContentTable 的所有字段，过滤静态字段
            for (Field field : ContentTable.class.getDeclaredFields()) {
                field.setAccessible(true); // 允许访问私有字段

                // 跳过静态字段
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                try {
                    Object value = field.get(contentTable); // 获取字段值
                    if (value != null) { // 如果字段不为空，添加查询条件
                        // 如果字段是 columnIds，使用模糊查询（like）
                        if ("columnIds".equals(field.getName())) {
                            predicates.add(criteriaBuilder.like(root.get("columnIds"), "%" + value + "%"));
                        } else {
                            predicates.add(criteriaBuilder.equal(root.get(field.getName()), value));
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 时间范围条件
            if (startDate != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(startDate)));
            }
            if (endDate != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), Timestamp.valueOf(endDate)));
            }

            // 设置排序规则
            if (pageable.getSort() == null || pageable.getSort().isEmpty()) {
                // 默认排序，先按照 sortOrder 排序，值越小越前，若为null则按 releaseTime 排序，时间越久越靠后
                Expression<Integer> sortOrderExpression = root.get("sortOrder");
                Expression<Date> releaseTimeExpression = root.get("releaseTime");

                // 处理sortOrder为null的情况
                Order sortOrderSort = criteriaBuilder.desc(criteriaBuilder.coalesce(sortOrderExpression, -1));

                // 处理releaseTime为null的情况，避免 LocalDateTime.MAX 溢出
                Expression<Object> safeReleaseTime = criteriaBuilder.selectCase()
                        .when(criteriaBuilder.isNull(releaseTimeExpression), Timestamp.valueOf("1000-12-31 23:59:59"))
                        .otherwise(releaseTimeExpression);

                Order releaseTimeSort = criteriaBuilder.desc(safeReleaseTime);

                // 将排序规则添加到查询中
                query.orderBy(sortOrderSort, releaseTimeSort);
            } else {
                // 如果 pageable 有排序条件，则使用 pageable 中的排序
                List<Order> orders = new ArrayList<>();
                pageable.getSort().forEach(order -> {
                    if (order.isAscending()) {
                        orders.add(criteriaBuilder.asc(root.get(order.getProperty())));
                    } else {
                        orders.add(criteriaBuilder.desc(root.get(order.getProperty())));
                    }
                });
                query.orderBy(orders);
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        }, pageable);

        // 构建并返回结果
        PageResult<ContentTable> result = new PageResult<>();
        result.setContent(page.getContent());
        result.setTotalElements(page.getTotalElements());
        return result;
    }




    @Override
    public List<ContentTable> findList(ContentTable contentTable) {
        return contentTableRepository.findAll(ContentTableSpecifications.queryList(contentTable));
    }

    @Override
    public ContentTable findById(Long id) {
        return contentTableRepository.findById(id).orElse(null);
    }

    @Override
    public ContentTable insert(ContentTable contentTable) {
        return contentTableRepository.save(contentTable);
    }

    @Override
    public ContentTable update(ContentTable contentTable) {
        return contentTableRepository.saveAndFlush(contentTable);
    }

    @Override
    public void delete(Long id) {
        contentTableRepository.deleteById(id);
    }

    @Override
    public void incrementViewCount(Long contentId) {
        contentTableRepository.incrementViewCount(contentId);
    }

    @Override
    public void incrementLikeCount(Long contentId) {
        contentTableRepository.incrementLikeCount(contentId);
    }

    @Override
    public Page<ContentTable> getContentsByColumnIds(String columnIds, Pageable pageable) {

        int pageNumber = pageable.getPageNumber(); // 从0开始
        int pageSize = pageable.getPageSize();

        // 计算 startRow / endRow
        int startRow = pageNumber * pageSize;
        int endRow = (pageNumber + 1) * pageSize;

        List<ContentTable> items = contentTableRepository.findByColumnIdsWithRowNumber(columnIds, startRow, endRow);
        long total = contentTableRepository.countByColumnIdsLike(columnIds);

        return new PageImpl<>(items, pageable, total);
    }


    @Override
    public Page<ContentTable> getContentsByColumnArray(String[] columnIds, Pageable pageable) {
        return contentTableRepository.findByColumnIdsIn(columnIds, pageable);
    }



/*    @Override
    public Page<ContentTable> searchByTitle(String title, Pageable pageable) {
        Page<ContentTable> contentPage = contentTableRepository.findByTitleContaining(title, pageable);

        // 对每个 ContentTable 填充 columnTables
        contentPage.forEach(content -> {
            if (content.getColumnIdsList() != null && !content.getColumnIdsList().isEmpty()) {
                List<ColumnTable> columns = columnTableRepository.findAllById(content.getColumnIdsList());
                content.setColumnTables(columns);
            }
        });

        return contentPage;
    }*/

    @Override
    public Page<ContentTable> searchByTitle(String title, Pageable pageable) {
        // 获取查询条件之前添加的排序信息
        Sort sort = pageable.getSort();

        // 确保分页查询时添加了自定义的排序规则
        if (!sort.isSorted()) {
            sort = Sort.by(
                    Sort.Order.asc("sortOrder").nullsLast(),      // sortOrder 排序，nullsLast
                    Sort.Order.desc("releaseTime").nullsLast()    // releaseTime 排序，nullsLast，时间最新排在前
            );
            pageable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);
        }

        // 分页查询内容，带上标题和状态过滤
        Page<ContentTable> contentPage = contentTableRepository.findByTitleContainingAndStatus(title, 1, pageable);

        // 对每个 ContentTable 填充 columnTables，并查找二级栏目
        contentPage.forEach(content -> {
            if (content.getColumnIdsList() != null && !content.getColumnIdsList().isEmpty()) {
                // 获取栏目列表
                List<ColumnTable> columns = columnTableRepository.findAllById(content.getColumnIdsList());
                content.setColumnTables(columns);

                // 获取第一个栏目并查找二级栏目
                if (!columns.isEmpty()) {
                    ColumnTable firstColumn = columns.get(0);
                    ColumnTable secondLevelColumn = findSecondLevelColumn(firstColumn);
                    content.setColumnTable(secondLevelColumn); // 假设 ContentTable 有 secondLevelColumn 字段
                }
            }
        });

        return contentPage;
    }

    private ColumnTable findSecondLevelColumn(ColumnTable column) {
        if (column == null) {
            return null;
        }

        // 获取父栏目
        ColumnTable parentColumn = columnTableRepository.findById(column.getParentColumnId()).orElse(null);

        // 如果父栏目不存在，返回 null
        if (parentColumn == null) {
            return null;
        }

        // 如果父栏目是顶级栏目（parentColumnId == 0）
        if (parentColumn.getParentColumnId() == 0) {
            return column;
        }

        // 否则递归查找父栏目
        return findSecondLevelColumn(parentColumn);
    }



    @Transactional
    @Override
    public void publishContent(Long id, Date releaseTime) {
        ContentTable content = contentTableRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("内容未找到"));

        content.setStatus(1); // 设置状态为1（发布）
        if (releaseTime != null) {
            content.setReleaseTime(releaseTime); // 设置发布时间
        } else {
            content.setReleaseTime(Timestamp.valueOf(LocalDateTime.now()));
        }

        contentTableRepository.save(content);
    }

    @Transactional
    @Override
    public void revokeContent(Long id) {
        ContentTable content = contentTableRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("内容未找到"));

        content.setStatus(2);
        contentTableRepository.saveAndFlush(content);
    }

    @Override
    public ContentTable addContent(ContentTable contentTable) {
        // 遍历所有列ID
        for (int i = 0; i < contentTable.getColumnIdsList().size(); i++) {
            // 获取当前的列ID
            Long columnId = contentTable.getColumnIdsList().get(i);

            // 1. 查询 ColumnTable 表，获取对应的 columnType
            ColumnTable column = columnTableRepository.findById(columnId)
                    .orElseThrow(() -> new RuntimeException("未找到对应的栏目ID : " + columnId));

            // 2. 判断 columnType 是否为 "singleArticle"
            if ("singleArticle".equalsIgnoreCase(column.getColumnType())) {
                // 3. 查询 content_table 是否已存在该类型的内容，状态为已发布（status = 1）
                List<ContentTable> existingContentWithSameColumn = contentTableRepository.findByColumnIdAndStatus(columnId);
                if (!existingContentWithSameColumn.isEmpty()) {
                    throw new IllegalArgumentException("该栏目已发布内容，不能重复发布！");
                }
            }
        }

    /*    if (contentTable.getStatus() == 1) {
            contentTable.setReleaseTime(Timestamp.valueOf(LocalDateTime.now()));
        }*/

        return contentTableRepository.save(contentTable);
    }

    @Override
    public Page<ContentTable> searchByColumnAndTitle(Long columnId, String title, Pageable pageable) {
        // 获取所有子级栏目 ID
        List<Long> allColumnIds = columnTableService.getAllSubColumnIds(columnId);

        // 分页查询所有符合条件的内容
        Page<ContentTable> contentPage = contentTableRepository.findAll((root, query, criteriaBuilder) -> {
            // 生成查询条件

            // 条件1：检查columnIds字段是否包含任意子栏目 ID
            Predicate columnPredicate = allColumnIds.stream()
                    .map(id -> criteriaBuilder.like(root.get("columnIds"), "%" + id + "%"))
                    .reduce(criteriaBuilder::or)
                    .orElseGet(criteriaBuilder::conjunction);

            // 条件2：基于title字段的模糊查询
            Predicate titlePredicate = criteriaBuilder.like(root.get("title"), "%" + title + "%");

            // 合并条件
            Predicate finalPredicate = criteriaBuilder.and(columnPredicate, titlePredicate);

            // 添加排序规则：首先根据 sortOrder 排序，若为null，则按 releaseTime 排序
            Expression<Integer> sortOrderExpression = root.get("sortOrder");
            Expression<Date> releaseTimeExpression = root.get("releaseTime");

            // 排序规则1：首先根据 sortOrder 排序，若为null，则按 releaseTime 排序
            Order sortOrderSort = criteriaBuilder.desc(criteriaBuilder.coalesce(sortOrderExpression, Integer.MIN_VALUE));

            // 排序规则2：按照 releaseTime 排序，若为null则排在最后
            Order releaseTimeSort = criteriaBuilder.desc(criteriaBuilder.coalesce(releaseTimeExpression, Timestamp.valueOf("1000-12-31 23:59:59")));

            // 组合排序规则
            query.orderBy(sortOrderSort, releaseTimeSort);

            // 返回最终的查询条件和排序规则
            return criteriaBuilder.and(finalPredicate);
        }, pageable);

        return contentPage;
    }



    @Override
    @Transactional
    public ContentTable updateContent(ContentTable contentTable) {
        // 1. 查询 ContentTable 实体对象，确认是否存在
        ContentTable existingContent = contentTableRepository.findById(contentTable.getContentId())
                .orElseThrow(() -> new RuntimeException("未找到对应的内容ID : " + contentTable.getContentId()));

        // 2. 如果修改了 columnTables 字段，需要进行单文档栏目类型的检查
        if (contentTable.getColumnIdsList() != null && !contentTable.getColumnIdsList().isEmpty()) {
            for (Long columnId : contentTable.getColumnIdsList()) {

                // 查询 ColumnTable 表，获取对应的 columnType
                ColumnTable columnTable = columnTableRepository.findById(columnId)
                        .orElseThrow(() -> new RuntimeException("未找到对应的栏目ID : " + columnId));

                // 判断 columnType 是否为 "singleArticle"
                if ("singleArticle".equalsIgnoreCase(columnTable.getColumnType())) {
                    // 查询 ContentTable 是否已有发布内容，避免重复添加
/*                    Optional<ContentTable> existingContentWithSameColumn = contentTableRepository.findByColumnIdAndStatus(columnId);
                    if (existingContentWithSameColumn.isPresent() && !existingContentWithSameColumn.get().getContentId().equals(contentTable.getContentId())) {
                        throw new IllegalArgumentException("该栏目已发布内容，不能重复发布！");
                    }*/

                    List<ContentTable> existingContentWithSameColumn = contentTableRepository.findByColumnIdAndStatus(columnId);
                    if (!existingContentWithSameColumn.isEmpty()) {
                        throw new IllegalArgumentException("该栏目已发布内容，不能重复发布！");
                    }
                }
            }
        }

        // 3. 更新内容属性（例如：标题、副标题等）
        existingContent.setTitle(contentTable.getTitle());
        existingContent.setSubtitle(contentTable.getSubtitle());
        existingContent.setBody(contentTable.getBody());
        existingContent.setCoverImage(contentTable.getCoverImage());
        existingContent.setLinkUrl(contentTable.getLinkUrl());
        existingContent.setIsDownloadable(contentTable.getIsDownloadable());
        existingContent.setStatus(contentTable.getStatus());
        existingContent.setAttachmentPath(contentTable.getAttachmentPath());
        existingContent.setViewCount(contentTable.getViewCount());
        existingContent.setLikeCount(contentTable.getLikeCount());
        existingContent.setIsPinned(contentTable.getIsPinned());
        existingContent.setSupportDownload(contentTable.getSupportDownload());
        existingContent.setFileType(contentTable.getFileType());
        existingContent.setColumnIdsList(contentTable.getColumnIdsList());
        existingContent.setReleaseTime(contentTable.getReleaseTime());
        existingContent.setSortOrder(contentTable.getSortOrder());

        // 4. 将 columnIdsList 转换为逗号分隔的字符串并赋值给 columnIds 字段
        if (contentTable.getColumnIdsList() != null && !contentTable.getColumnIdsList().isEmpty()) {
            String columnIds = contentTable.getColumnIdsList().stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            existingContent.setColumnIds(columnIds);
        } else {
            existingContent.setColumnIds(null);
        }
        contentTable.prePersist(); // 强制调用预处理方法
        // 6. 保存更新后的内容
        return contentTableRepository.saveAndFlush(existingContent);
    }

    @Override
    public Page<ContentTable> getContentsByColumnIdsToTile(String columnIds, Pageable pageable) {
        return contentTableRepository.findByColumnIdsLikeToTile(columnIds, pageable);
    }

}
